const fs = require('fs').promises;
const path = require('path');

// 解析Markdown文件，提取标题和内容
async function parseMarkdownToTable(content, currentFile) {
  const lines = content.split('\n');
  const tableData = [];
  let currentSection = '';
  let ruleNumber = '';
  let ruleText = '';
  let ruleLevel = '';
  let ruleScope = '';
  let languageStandard = '';
  let performance = '';
  let interpretation = '';
  let exceptions = '';
  let fixSuggestion = '';
  let testCases = '';
  let isCollectingSection = false;
  let isInTable = false;

  // 表头
  tableData.push(['规则编号', '规则文本', '规则等级', '分析范围', '语言标准', '性能表现', '规则释义', '例外情况', '修复或避错建议']);
  // 分隔行
  tableData.push(['---', '---', '---', '---', '---', '---', '---', '---', '---']);

  function addRuleToTable() {
    if (ruleNumber) {
      tableData.push([
        ruleNumber,
        ruleText || '',
        ruleLevel || '',
        ruleScope || '',
        languageStandard || '',
        performance || '',
        interpretation.trim() || '',
        exceptions.trim() || '',
        fixSuggestion.trim() || ''
      ]);

      // 如果有测试样例，保存到单独的文件
      if (testCases.trim()) {
        saveTestCase(ruleNumber, testCases.trim(), currentFile);
      }
    }
  }

  async function saveTestCase(ruleNumber, content, file) {
    const testFilePath = path.join('output-table', 'Testfile', `${ruleNumber.toLowerCase()}-testfile.md`);
    try {
      await fs.mkdir(path.join('output-table', 'Testfile'), { recursive: true });
      // 添加规则标题和适当的空行
      const contentWithTitle = `# 规则 ${ruleNumber}

## 测试样例

### Testfile ${ruleNumber.replace('-', '_')}.java

${content}`;
      await fs.writeFile(testFilePath, contentWithTitle, 'utf-8');
    } catch (error) {
      console.error(`Error saving test case for ${ruleNumber}:`, error);
    }
  }

  for (let i = 0; i < lines.length; i++) {
    const line = lines[i].trim();
    const nextLine = i < lines.length - 1 ? lines[i + 1].trim() : '';
    
    if (line.startsWith('# 规则')) {
      // 如果已经有规则数据，先添加到表格中
      addRuleToTable();
      
      // 提取规则编号并重置所有字段
      ruleNumber = line.replace('# 规则', '').trim();
      ruleText = '';
      ruleLevel = '';
      ruleScope = '';
      languageStandard = '';
      performance = '';
      interpretation = '';
      exceptions = '';
      fixSuggestion = '';
      testCases = '';
      isCollectingSection = false;
      isInTable = false;
    } else if (line.startsWith('|')) {
      // 处理表格行
      isInTable = true;
      if (!line.includes('---')) {
        const cells = line.split('|').map(cell => cell.trim()).filter(cell => cell);
        if (cells.length >= 2) {
          const [key, value] = cells;
          switch (key) {
            case '规则文本':
              ruleText = value;
              break;
            case '规则等级':
              ruleLevel = value;
              break;
            case '分析范围':
              ruleScope = value;
              break;
            case '语言标准':
              languageStandard = value;
              break;
            case '性能表现':
              performance = value;
              break;
          }
        }
      }
    } else if (line === '## 规则释义') {
      isInTable = false;
      isCollectingSection = true;
      currentSection = 'interpretation';
    } else if (line === '## 例外情况') {
      isCollectingSection = true;
      currentSection = 'exceptions';
    } else if (line === '## 修复或避错建议') {
      isCollectingSection = true;
      currentSection = 'fixSuggestion';
    } else if (line === '## 测试样例') {
      isCollectingSection = true;
      currentSection = 'testCases';
    } else if (isCollectingSection && line !== '' && !line.startsWith('###')) {
      // 根据当前section收集内容
      if (currentSection === 'interpretation' && !line.startsWith('#')) {
        interpretation += line + ' ';
      } else if (currentSection === 'exceptions' && !line.startsWith('#')) {
        exceptions += line + ' ';
      } else if (currentSection === 'fixSuggestion' && !line.startsWith('#')) {
        fixSuggestion += line + ' ';
      } else if (currentSection === 'testCases') {
        if (line.startsWith('```')) {
          // 保持代码块标记和语言标识
          testCases += line + '\n';
        } else {
          // 保持原始的空格和换行
          testCases += lines[i] + '\n';
        }
      }
    }
  }

  // 确保最后一个规则也被添加到表格中
  addRuleToTable();

  return tableData;
}

// 将数组转换为Markdown表格格式
function arrayToMarkdownTable(tableData) {
  return tableData.map(row => `| ${row.join(' | ')} |`).join('\n');
}

// 主函数
async function processMarkdownFiles() {
  try {
    // 创建output-table目录（如果不存在）
    await fs.mkdir('output-table', { recursive: true });
    
    // 读取files目录下的所有md文件
    const files = await fs.readdir('standard-md-files');
    const mdFiles = files.filter(file => file.endsWith('.md'));
    
    // 用于存储所有规则数据的数组
    let allTableData = [
      ['规则编号', '规则文本', '规则等级', '分析范围', '语言标准', '性能表现', '规则释义', '例外情况', '修复或避错建议'],
      ['---', '---', '---', '---', '---', '---', '---', '---', '---']
    ];
    
    for (const file of mdFiles) {
      // 读取文件内容
      const content = await fs.readFile(path.join('standard-md-files', file), 'utf-8');
      
      // 解析内容
      const tableData = await parseMarkdownToTable(content, file);
      // 跳过表头和分隔行，只添加规则数据
      allTableData = allTableData.concat(tableData.slice(2));
      
      console.log(`Processed ${file} successfully`);
    }
    
    // 将所有规则数据转换为Markdown表格并写入单个文件
    const markdownTable = arrayToMarkdownTable(allTableData);
    await fs.writeFile(
      path.join('output-table', 'bugfinder-rules.md'),
      markdownTable,
      'utf-8'
    );
    
    console.log('All files processed and combined successfully');
  } catch (error) {
    console.error('Error processing files:', error);
    throw error; // 抛出错误以便调用者处理
  }
}

// 导出函数
module.exports = { processMarkdownFiles };

// 如果直接运行此文件，则执行主函数
if (require.main === module) {
  processMarkdownFiles();
}